package com.bolt.gateway.filter;

import com.bolt.gateway.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by Administrator on 2019/12/12.
 */
@Slf4j
public class RequestFilter  implements GlobalFilter, Ordered {

    public static final String LOG_TRACE_ID = "traceId";

    public static final String LOG_B3_TRACEID = "X-B3-TraceId";


    public static final String TOKEN_HEADER = "Authorization" ;
    /**
     * 请求头跟踪id名。
     */
    public static final String HTTP_HEADER_TRACE_ID = "app_trace_id";
    @Override
    public int getOrder() {
        // TODO Auto-generated method stub
        return -501;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String traceId = MDC.get(LOG_B3_TRACEID);
        MDC.put(LOG_TRACE_ID, traceId);

        String accessToken = TokenUtil.extractToken(exchange.getRequest());

        //构建head
        ServerHttpRequest traceHead = exchange.getRequest().mutate()
                .header(HTTP_HEADER_TRACE_ID, traceId )
                .header(TOKEN_HEADER, accessToken ).build();
        //将现在的request 变成 change对象

        log.info("request url = " + exchange.getRequest().getURI() + ", traceId = " + traceId);

        ServerWebExchange build = exchange.mutate().request(traceHead).build();





        return chain.filter(build);


    }
}

 